package com.denlaku.longan.controller.impl;

import com.denlaku.longan.anno.VarBy;
import com.denlaku.longan.controller.TenantMemObjPermController;
import com.denlaku.longan.core.Current;
import com.denlaku.longan.http.Resp;
import com.denlaku.longan.http.Return;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.service.ObjectTagSetService;
import com.denlaku.longan.service.TenantMemObjPermService;
import com.denlaku.longan.service.UserService;
import com.denlaku.longan.vo.ObjectTagSet;
import com.denlaku.longan.vo.TenantMemObjPerm;
import com.denlaku.longan.vo.User;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author tianx
 */
@RestController
public class TenantMemObjPermControllerImpl implements TenantMemObjPermController {
    @Autowired
    private TenantMemObjPermService tenantMemObjPermService;

    @Autowired
    private UserService userService;

    @Autowired
    private ObjectTagSetService objPermSetService;

    @Override
    public Return<Void> batchAdd(List<TenantMemObjPerm> list) {
        tenantMemObjPermService.batchAdd(list);
        return Resp.success();
    }

    @Override
    @VarBy
    public Return<List<TenantMemObjPerm>> list(Long userId) {
        Long tenantId = Current.getTenantId();
        List<TenantMemObjPerm> list = tenantMemObjPermService.list(tenantId, userId);
        setPermSetName(list);

        Set<Long> userIds = list.stream().map(TenantMemObjPerm::getUserId).collect(Collectors.toSet());
        Map<Long, User> userMap = userService.listBaseInfoMap(userIds);
        return Resp.success(list).setUmap(userMap);
    }

    private void setPermSetName(List<TenantMemObjPerm> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Set<Long> permSetIds = list.stream().map(TenantMemObjPerm::getTagSetId).collect(Collectors.toSet());
        List<ObjectTagSet> permSetList = objPermSetService.list(Query.of(permSetIds));
        Map<Long, String> permSetNameMap = permSetList.stream()
            .collect(Collectors.toMap(ObjectTagSet::getId, ObjectTagSet::getName));
        list.forEach(perm -> perm.setTagSetName(permSetNameMap.get(perm.getTagSetId())));
    }

    @Override
    public Return<Void> delete(Long id) {
        Long tenantId = Current.getTenantId();
        tenantMemObjPermService.delete(tenantId, id);
        return Resp.success();
    }
}
